package com.cccyy.date;

import java.time.*;
import java.time.format.DateTimeFormatter;

public class DateFormat {
    public static void main(String[] args) {
        dateTimeFormatter();
    }

    private static void dateTimeFormatter() {
        LocalDateTime now = LocalDateTime.now();
        System.out.println("LocalDateTime：" + now);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formatted = formatter.format(now);
        System.out.println(formatted);

        ZonedDateTime zonedDateTime = ZonedDateTime.now();
        System.out.println("ZonedDateTime：" + zonedDateTime);
        String formatted2 = formatter.format(zonedDateTime);
        System.out.println(formatted2);

        Instant now2 = Instant.now();
        System.out.println("Instant：" + now2);
        DateTimeFormatter formatter3 = DateTimeFormatter.ISO_INSTANT;
        String formatted3 = formatter3.format(now2.atZone(ZoneId.systemDefault()));
        System.out.println(formatted3);


        String s = convertBirthday("1992年2月24日");
        System.out.println(s);
    }


    private static String convertBirthday(String birthday) {
        String s = convertDateFormat(birthday, DateTimeFormatter.ofPattern("yyyy年M月d日"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        if (s == null) {
            s = convertDateFormat(birthday, DateTimeFormatter.ofPattern("yyyyMMdd"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }

        if (s == null) {
            LocalDate.parse(birthday, DateTimeFormatter.ofPattern("yyyy-MM-dd")); //验证是否是这种格式，如果是的话直接返回
            s = birthday;
        }

        return s;
    }

    private static String convertDateFormat(String date, DateTimeFormatter sourceFormatter,
                                            DateTimeFormatter targetFormatter) {
        try {
            return LocalDate.parse(date, sourceFormatter).format(targetFormatter);
        } catch (Exception e) {
            return null;
        }
    }
}
